package com.cryptape.cita_wallet.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.R;
import com.cryptape.cita.protocol.core.methods.response.AppSendTransaction;
import com.cryptape.cita_wallet.activity.transfer.EntrustTransferPresenter;
import com.cryptape.cita_wallet.activity.transfer.TransferView;
import com.cryptape.cita_wallet.bean.AddDataItem;
import com.cryptape.cita_wallet.constant.ConstantUtil;
import com.cryptape.cita_wallet.event.TransferPushEvent;
import com.cryptape.cita_wallet.item.Token;
import com.cryptape.cita_wallet.item.Wallet;
import com.cryptape.cita_wallet.item.transaction.AppTransaction;
import com.cryptape.cita_wallet.service.http.EthRpcService;
import com.cryptape.cita_wallet.service.http.WalletService;
import com.cryptape.cita_wallet.util.AddressUtil;
import com.cryptape.cita_wallet.util.Blockies;
import com.cryptape.cita_wallet.util.CurrencyUtil;
import com.cryptape.cita_wallet.util.NumberUtil;
import com.cryptape.cita_wallet.util.ether.EtherUtil;
import com.cryptape.cita_wallet.util.permission.PermissionUtil;
import com.cryptape.cita_wallet.util.permission.RuntimeRationale;
import com.cryptape.cita_wallet.util.qrcode.CodeUtils;
import com.cryptape.cita_wallet.view.CompressEditText;
import com.cryptape.cita_wallet.view.LockTypePopupWindow;
import com.cryptape.cita_wallet.view.TitleBar;
import com.cryptape.cita_wallet.view.button.CommonButton;
import com.cryptape.cita_wallet.view.dialog.ToastDoubleButtonDialog;
import com.cryptape.cita_wallet.view.dialog.TransferDialog;
import com.cryptape.cita_wallet.view.dialog.listener.OnDialogCancelClickListener;
import com.cryptape.cita_wallet.view.dialog.listener.OnDialogOKClickListener;
import com.cryptape.cita_wallet.view.tool.CytonTextWatcher;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

;

/**
 * Created by dengming on 13/1/20.
 */

public class EntrustActivity extends NBaseActivity implements TransferView {

    private static final int REQUEST_CODE_SCAN = 0x01;
    private static final int REQUEST_CODE_TRANSACTION = 0x02;
    public static final String EXTRA_TOKEN = "extra_token";
    public static final String EXTRA_ADDRESS = "extra_address";

    private EntrustTransferPresenter mPresenter;

    private TextView walletAddressText, walletNameText, feeValueText, balanceText, hmio_balance_text;
    private ImageView scanImage;
    private CompressEditText mCetReceiverAddress;
    private AppCompatEditText transferValueEdit;
    private AppCompatEditText transferValueEdit1;
    private CommonButton nextActionButton;
    private CircleImageView photoImage;
    private ProgressBar progressBar;

    private TitleBar titleBar;
    private TransferDialog transferDialog;
    private AppTransaction mAppTransaction = new AppTransaction();
    private TextView lock_type;
    private RelativeLayout rl_deposit_2;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_entrust;
    }

    @Override
    protected void initView() {
        scanImage = findViewById(R.id.transfer_address_scan);
        nextActionButton = findViewById(R.id.next_action_button);
        walletAddressText = findViewById(R.id.wallet_address);
        walletNameText = findViewById(R.id.wallet_name);
        balanceText = findViewById(R.id.tv_currency_incentive);
        hmio_balance_text = findViewById(R.id.hmio_balance_text);
        feeValueText = findViewById(R.id.fee_value_text);
        mCetReceiverAddress = findViewById(R.id.cet_address);
        transferValueEdit = findViewById(R.id.transfer_value);
        transferValueEdit1 = findViewById(R.id.transfer_value_1);
        photoImage = findViewById(R.id.wallet_photo);
        titleBar = findViewById(R.id.title);
        lock_type = findViewById(R.id.lock_type);
        rl_deposit_2 = findViewById(R.id.rl_deposit_2);
    }

    @Override
    protected void initData() {
        mPresenter = new EntrustTransferPresenter(EntrustActivity.this, this);
    }

    @Override
    public void updateTitleData(String title) {
        titleBar.setTitle(title);
    }

    @Override
    public void updateWalletData(Wallet wallet) {
        walletAddressText.setText(wallet.address);
        walletNameText.setText(wallet.name);
        photoImage.setImageBitmap(Blockies.createIcon(wallet.address));
    }

    @Override
    public void updaterReceiveAddress(String address) {
        mCetReceiverAddress.setText(address);
        isAddressOk = AddressUtil.isAddressValid(address.toString());
    }

    @Override
    public void updateAnyTokenBalance(Double balance) {
        balanceText.setText(String.format(getString(R.string.transfer_balance_place_holder),
                CurrencyUtil.fmtMicrometer(NumberUtil.getDecimalValid_8(balance)) + " " + mPresenter.getTokenItem().getSymbol()));
    }

    public void updateMixHTokenBalance(Double balance) {
        hmio_balance_text.setText(String.format(getString(R.string.transfer_balance_place_holder),
                CurrencyUtil.fmtMicrometer(NumberUtil.getDecimalValid_8(balance)) + " " + mPresenter.mToken1.getSymbol()));
    }

    @Override
    public void updateNativeTokenBalance(Double balance) {
        balanceText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mPresenter.isTransferFeeEnough()) {
                    Toast.makeText(mActivity, String.format(getString(R.string.balance_more_gas),
                            mPresenter.getFeeTokenUnit()), Toast.LENGTH_SHORT).show();
                    return;
                }
                transferValueEdit.setText(mPresenter.balanceSubFee());
            }
        });
    }

    @Override
    public void startUpdateEthGasPrice() {
        showProgressCircle();
    }

    @Override
    public void updateEthGasPriceSuccess(BigInteger gasPrice) {
        dismissProgressCircle();

    }

    @Override
    public void updateEthGasPriceFail(Throwable throwable) {
        Toast.makeText(mActivity, throwable.getMessage(), Toast.LENGTH_SHORT).show();
        dismissProgressCircle();
    }

    @Override
    public void initTransferFeeView() {
        feeValueText.setText(mPresenter.getTransferFee());
        initAdvancedSetup();
    }

    @Override
    public void updateCITAQuota(String quotaFee) {
        feeValueText.setText(quotaFee);
    }

//    public boolean checkTransferValueMoreBalance(String transferValue) {
//
//        if(TextUtils.isEmpty(mPresenter.mType))
//        {
//            return Double.parseDouble(transferValue) - 500>=0;
//        }
//        return true;
//    }

    public boolean checkBalance(String transferValue, String transferValue1) {

        if (TextUtils.isEmpty(mPresenter.mType) && !TextUtils.isEmpty(mType) && mType.equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
            if (TextUtils.isEmpty(transferValue1)) {
                Toast.makeText(mActivity, R.string.transfer_amount_not_null, Toast.LENGTH_SHORT).show();
                return false;
            }
            double mValue = 0;
            try {
                mValue = Double.parseDouble(transferValue);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Toast.makeText(mActivity, R.string.transfer_amount_not_null, Toast.LENGTH_SHORT).show();
                return false;
            }
            if (mValue > mPresenter.mTokenBalance) {
                Toast.makeText(mActivity, R.string.balance_no_enough, Toast.LENGTH_SHORT).show();
                return false;
            }
            double hValue = 0;
            try {
                hValue = Double.parseDouble(transferValue1);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Toast.makeText(mActivity, R.string.transfer_amount_not_null, Toast.LENGTH_SHORT).show();
                return false;
            }
            if (hValue > mPresenter.mTokenHBalance) {
                Toast.makeText(mActivity, R.string.balance_no_enough, Toast.LENGTH_SHORT).show();
                return false;
            }
            if (mValue + hValue < 500) {
                Toast.makeText(mActivity, R.string.tip_small_entrust, Toast.LENGTH_SHORT).show();
                return false;
            }
//            return (mValue +hValue - 500)>=0;
        } else {
            double mValue = 0;
            try {
                mValue = Double.parseDouble(transferValue);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Toast.makeText(mActivity, R.string.transfer_amount_not_null, Toast.LENGTH_SHORT).show();
                return false;
            }
            if (mValue > mPresenter.mTokenBalance) {
                Toast.makeText(mActivity, R.string.balance_no_enough, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }


    @Override
    protected void initAction() {
        scanImage.setOnClickListener((view) -> {
            AndPermission.with(mActivity)
                    .runtime().permission(Permission.Group.CAMERA)
                    .rationale(new RuntimeRationale())
                    .onGranted(permissions -> {
                        Intent intent = new Intent(mActivity, QrCodeActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    })
                    .onDenied(permissions -> PermissionUtil.showSettingDialog(mActivity, permissions))
                    .start();
        });

        nextActionButton.setOnClickListener(v -> {
            String receiveAddressValue = mCetReceiverAddress.getText();
            String transferValue = transferValueEdit.getText().toString().trim();
            String transferValue1 = transferValueEdit1.getText().toString().trim();
            try {
                Double.parseDouble(transferValue);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(receiveAddressValue)) {
                Toast.makeText(mActivity, R.string.transfer_address_not_null, Toast.LENGTH_SHORT).show();
            } else if (!AddressUtil.isAddressValid(receiveAddressValue)) {
                Toast.makeText(mActivity, R.string.address_error, Toast.LENGTH_LONG).show();
            } else if (TextUtils.isEmpty(transferValue)) {
                Toast.makeText(mActivity, R.string.transfer_amount_not_null, Toast.LENGTH_SHORT).show();
            } else if (!mPresenter.isTransferFeeEnough()) {
                Toast.makeText(mActivity, String.format(getString(R.string.balance_not_enough_fee),
                        mPresenter.getFeeTokenUnit()), Toast.LENGTH_SHORT).show();
            } else if (!checkBalance(transferValue, transferValue1)) {
//                Toast.makeText(this,getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();
//                handleBigTransferValue();
//                Toast.makeText(mActivity, R.string.tip_small_entrust, Toast.LENGTH_SHORT).show();
            } else {
//                Toast.makeText(this,getString(R.string.Not_open_yet),Toast.LENGTH_SHORT).show();

                getConfirmTransferView();
            }
        });

        lock_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<AddDataItem> data = new ArrayList<>();
                LockTypePopupWindow popupWindow = new LockTypePopupWindow(EntrustActivity.this, data);
                popupWindow.showAsDropDown(lock_type, 0, 10);
            }
        });
    }

    private String mType = EntrustTransferPresenter.TYPE_LOCK_NATURE;

    public void setLockType1(String type) {
        if (type == null) {
            lock_type.setEnabled(true);
        } else {
            lock_type.setText(type);
            lock_type.setEnabled(false);
        }
        if (type.equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
            mType = EntrustTransferPresenter.TYPE_LOCK_NATURE;
            mPresenter.getTokenItem().setContractAddress(ConstantUtil.getMGPToken());
            mPresenter.getTokenItem().symbol = ConstantUtil.getMGPName();
//            mCetReceiverAddress.setText(ConstantUtil.getMGPToken());
            mPresenter.getTokenBalance();
        } else if (type.equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
            mType = EntrustTransferPresenter.TYPE_LOCK_EMPTY;
            mPresenter.getTokenItem().setContractAddress(ConstantUtil.getHToken());
            mPresenter.getTokenItem().symbol = ConstantUtil.HMIO_TOKEN_NAME;
//            mCetReceiverAddress.setText(ConstantUtil.getHToken());
            mPresenter.getTokenBalance();
        }
    }

    public void setLockType(String type) {
        lock_type.setText(type);
        if (type.equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
            mType = EntrustTransferPresenter.TYPE_LOCK_NATURE;
            mPresenter.getTokenItem().setContractAddress(ConstantUtil.getMGPToken());
            mPresenter.getTokenItem().symbol = ConstantUtil.getMGPName();
            mPresenter.mToken1 = null;
            transferValueEdit.setEnabled(true);
            transferValueEdit1.setVisibility(View.GONE);
            rl_deposit_2.setVisibility(View.GONE);
//            mCetReceiverAddress.setText(ConstantUtil.getMGPToken());
            mPresenter.getTokenBalance();
        } else if (type.equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
            mPresenter.mToken1 = null;
            mType = EntrustTransferPresenter.TYPE_LOCK_EMPTY;
            mPresenter.getTokenItem().setContractAddress(ConstantUtil.getHToken());
            mPresenter.getTokenItem().symbol = ConstantUtil.HMIO_TOKEN_NAME;
            transferValueEdit.setEnabled(true);
            transferValueEdit1.setVisibility(View.GONE);
            rl_deposit_2.setVisibility(View.GONE);
//            mCetReceiverAddress.setText(ConstantUtil.getHToken());
            mPresenter.getTokenBalance();
        } else if (type.equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
            Token token1 = new Token();
            token1.setChainId("-105");
            token1.symbol = ConstantUtil.HMIO_TOKEN_NAME;
            token1.name = ConstantUtil.HMIO_TOKEN_NAME;
            token1.decimals = 18;
            token1.setContractAddress(ConstantUtil.getHToken());
//            mPresenter.mToken1 = token1;
            mType = EntrustTransferPresenter.TYPE_LOCK_MIX;
            if (!TextUtils.isEmpty(mPresenter.mType)) {
                transferValueEdit.setEnabled(true);
                transferValueEdit1.setVisibility(View.GONE);
                rl_deposit_2.setVisibility(View.GONE);
            } else {
                transferValueEdit.setEnabled(false);
                transferValueEdit1.setVisibility(View.VISIBLE);
                rl_deposit_2.setVisibility(View.VISIBLE);
                mPresenter.mToken1 = token1;
            }
//            transferValueEdit1.setVisibility(View.VISIBLE);
//            rl_deposit_2.setVisibility(View.VISIBLE);
//            mPresenter.getTokenItem().setContractAddress(ConstantUtil.getHToken());
//            mPresenter.getTokenItem().symbol=ConstantUtil.HMIO_TOKEN_NAME;
//            mCetReceiverAddress.setText(ConstantUtil.getHToken());
            mPresenter.getTokenBalance();
        }
    }

    /**
     * If balance of wallet is more than gas fee, neuron will show dialog to give user two choices
     */
    private void handleBigTransferValue() {
        ToastDoubleButtonDialog dialog = ToastDoubleButtonDialog.getInstance(mActivity,
                getString(R.string.all_balance_transfer_tip));
        dialog.setOnOkClickListener(new OnDialogOKClickListener() {
            @Override
            public void onClick(Dialog dialog) {
                transferValueEdit.setText(mPresenter.balanceSubFee());
                getConfirmTransferView();
                dialog.dismiss();
            }
        });
        dialog.setOnCancelClickListener(new OnDialogCancelClickListener() {
            @Override
            public void onClick(Dialog dialog) {
                transferValueEdit.setText("");
                dialog.dismiss();
            }
        });
    }


    /**
     * Estimate Gas limit when address edit text and value edit text were not null
     */
    private boolean isAddressOk = false;
    private boolean isValueOk = false;
    private boolean isValue1Ok = false;
    private boolean isNeedListen = true;

    @Override
    public void initTransferEditValue() {
        mCetReceiverAddress.setTextWatcher(new CytonTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                isAddressOk = AddressUtil.isAddressValid(s.toString());
                updateTransferEditValue();
            }
        });
        transferValueEdit.addTextChangedListener(new CytonTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!isNeedListen) {
                    return;
                }
                super.afterTextChanged(s);
                try {
                    if (!TextUtils.isEmpty(s)) {
                        Double.parseDouble(s.toString());
                        isValueOk = true;
                        updateTransferEditValue();
                        if (mType == EntrustTransferPresenter.TYPE_LOCK_MIX && mPresenter.mBean != null) {
                            BigDecimal mValue = new BigDecimal(s.toString());
                            BigDecimal rateH = new BigDecimal(mPresenter.mBean.getRateH());
                            BigDecimal rateM = new BigDecimal(mPresenter.mBean.getRateM());
                            BigDecimal hValue = mValue.multiply(rateH).divide(rateM, 0, BigDecimal.ROUND_DOWN);
                            isNeedListen = false;
                            transferValueEdit1.setText(hValue.toString());
                            isNeedListen = true;
                        }
                    } else {
                        isValueOk = false;
                        Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    isValueOk = false;
                    Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
                }
            }
        });

        transferValueEdit1.addTextChangedListener(new CytonTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!isNeedListen) {
                    return;
                }
                super.afterTextChanged(s);
                try {
                    if (!TextUtils.isEmpty(s)) {
                        Double.parseDouble(s.toString());
                        isValue1Ok = true;
                        if (mType == EntrustTransferPresenter.TYPE_LOCK_MIX && mPresenter.mBean != null) {
                            BigDecimal hValue = new BigDecimal(s.toString());
                            BigDecimal rateH = new BigDecimal(mPresenter.mBean.getRateH());
                            BigDecimal rateM = new BigDecimal(mPresenter.mBean.getRateM());
                            BigDecimal mValue = hValue.multiply(rateM).divide(rateH, 0, BigDecimal.ROUND_FLOOR);
                            isNeedListen = false;
                            transferValueEdit.setText(mValue.toString());
                            isNeedListen = true;
                        }
                    } else {
                        isValue1Ok = false;
                        Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    isValue1Ok = false;
                    Toast.makeText(mActivity, R.string.input_correct_value_tip, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void updateTransferEditValue() {
        if (isAddressOk && isValueOk) {
            initAdvancedSetup();
//            mPresenter.initGasLimit(getTransactionInfo());
//            mPresenter.initGasLimit(getLockTransactionInfo());
        }
    }

    private void updateTransferEditValue1() {
        if (isAddressOk && isValue1Ok) {
            initAdvancedSetup();
            mPresenter.initGasLimit(getTransactionInfo());
        }
    }

    private AppTransaction getTransactionInfo() {

        AppTransaction appTransaction = new AppTransaction(mPresenter.getTokenItem().getContractAddress(), "0");
        appTransaction.data = EthRpcService.createTokenTransferData(mCetReceiverAddress.getText(),
                Convert.toWei(transferValueEdit.getText().toString(), Convert.Unit.ETHER).toBigInteger());
        return appTransaction;
    }

    private AppTransaction getLockTransactionInfo() {
        AppTransaction appTransaction = new AppTransaction(ConstantUtil.DEPOSIT_CONTRACT, "0");
        if (mType.equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
            if (mPresenter.mType != null && mPresenter.mType.equals(EntrustTransferPresenter.TYPE_LOCK_NATURE)) {
                appTransaction.data = EthRpcService.createLockAppandData("", null);
            } else {
                appTransaction.data = EthRpcService.createLockTransferData("", null);

            }
        } else if (mType.equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
            if (mPresenter.mType != null && mPresenter.mType.equals(EntrustTransferPresenter.TYPE_LOCK_EMPTY)) {
                appTransaction.data = EthRpcService.createLockAppandData("", null);

            } else {
                appTransaction.data = EthRpcService.createLockEmpyTransferData("", null);

            }
        } else if (mType.equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
            if (mPresenter.mType != null && mPresenter.mType.equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
                appTransaction.data = EthRpcService.createLockAppandData("", null);
            } else {
                appTransaction.data = EthRpcService.createLockMixTransferData("", null);
            }
        }

//        appTransaction.to = ConstantUtil.DEPOSIT_CONTRACT;
        appTransaction.value = null;
        appTransaction.isContract = true;
//        appTransaction.data = EthRpcService.createTokenTransferData(mCetReceiverAddress.getText(),
//                Convert.toWei(transferValueEdit.getText().toString(), Convert.Unit.ETHER).toBigInteger());
        return appTransaction;
    }


    private void initAdvancedSetup() {
        feeValueText.setTextColor(ContextCompat.getColor(mActivity, R.color.colorPrimary));
        feeValueText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, AdvanceSetupActivity.class);
                intent.putExtra(AdvanceSetupActivity.EXTRA_TRANSFER, true);
                intent.putExtra(AdvanceSetupActivity.EXTRA_NATIVE_TOKEN, mPresenter.isNativeToken());
                mAppTransaction.chainType = mPresenter.isEther() ? ConstantUtil.TYPE_ETH : ConstantUtil.TYPE_CITA;
                mAppTransaction.data = mPresenter.getData();
                if (mPresenter.isEther()) {
                    mAppTransaction.setGasLimit(mPresenter.getGasLimit());
                    mAppTransaction.setGasPrice(mPresenter.getGasPrice());
                    mAppTransaction.chainId = EtherUtil.getEtherId();
                } else {
                    mAppTransaction.chainId = mPresenter.getTokenItem().getChainId();
                    mAppTransaction.setQuota(mPresenter.getQuotaLimit().toString());
                }
                intent.putExtra(AdvanceSetupActivity.EXTRA_ADVANCE_SETUP, mAppTransaction);
                startActivityForResult(intent, REQUEST_CODE_TRANSACTION);
            }
        });
    }

    /**
     * show confirm transfer view
     */
    private void getConfirmTransferView() {
        if (isFastDoubleClick()) return;
        String transferValue = transferValueEdit.getText().toString().trim();
        String transferValue1 = transferValueEdit1.getText().toString().trim();
        String receiveAddress = mCetReceiverAddress.getText();
        transferDialog = new TransferDialog(this, (password, progressBar) -> {
            this.progressBar = progressBar;
            transferDialog.setButtonClickAble(false);
            progressBar.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(password)) {
                transferDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_not_null, Toast.LENGTH_SHORT).show();
            } else if (!WalletService.checkPassword(mActivity, password, mPresenter.getWalletItem())) {
                transferDialog.setButtonClickAble(true);
                progressBar.setVisibility(View.GONE);
                Toast.makeText(mActivity, R.string.password_fail, Toast.LENGTH_SHORT).show();
            } else {
//                transferDialog.setButtonClickAble(false);
//                progressBar.setVisibility(View.VISIBLE);
                if (mType.equals(EntrustTransferPresenter.TYPE_LOCK_MIX)) {
                    mPresenter.execMixLock(this, mPresenter.getTokenItem(), receiveAddress, transferValue, transferValue1, password);
                } else {
                    mPresenter.handleEntrustTransferAction(password, transferValue, receiveAddress, mType);
                }
            }
        });
        transferDialog.setConfirmData(getString(R.string.commission_details), mPresenter.getWalletItem().address, receiveAddress,
                NumberUtil.getDecimalValid_8(Double.parseDouble(transferValue)) + mPresenter.getTokenItem().getSymbol(),
                feeValueText.getText().toString());
        if (mPresenter.mToken1 != null) {
            transferDialog.setTransferValue1(NumberUtil.getDecimalValid_8(Double.parseDouble(transferValue1)) + mPresenter.mToken1.getSymbol());
        }
    }


    @Override
    public void transferCITASuccess(AppSendTransaction appSendTransaction) {
        progressBar.setVisibility(View.GONE);
        if (appSendTransaction == null) {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        } else if (appSendTransaction.getError() != null
                && !TextUtils.isEmpty(appSendTransaction.getError().getMessage())) {
            Toast.makeText(mActivity, appSendTransaction.getError().getMessage(),
                    Toast.LENGTH_SHORT).show();
        } else if (!TextUtils.isEmpty(appSendTransaction.getSendTransactionResult().getHash())) {
            Toast.makeText(EntrustActivity.this, R.string.transfer_success, Toast.LENGTH_SHORT).show();
            transferDialog.dismiss();
            EventBus.getDefault().post(new TransferPushEvent());
            finish();
        } else {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void transferCITAFail(Throwable e) {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(EntrustActivity.this,
                e.getMessage(), Toast.LENGTH_SHORT).show();
        transferDialog.dismiss();
    }

    @Override
    public void transferEtherSuccess(EthSendTransaction ethSendTransaction) {
        progressBar.setVisibility(View.GONE);
        if (ethSendTransaction == null) {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        } else if (ethSendTransaction.getError() != null
                && !TextUtils.isEmpty(ethSendTransaction.getError().getMessage())) {
            Toast.makeText(mActivity, ethSendTransaction.getError().getMessage(),
                    Toast.LENGTH_SHORT).show();
        } else if (!TextUtils.isEmpty(ethSendTransaction.getTransactionHash())) {
            Toast.makeText(mActivity, R.string.transfer_success, Toast.LENGTH_SHORT).show();
            transferDialog.dismiss();
            EventBus.getDefault().post(new TransferPushEvent());
            finish();
        } else {
            Toast.makeText(mActivity, R.string.transfer_fail, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void transferEtherFail(String message) {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
        transferDialog.dismiss();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (transferDialog != null) {
            transferDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCAN:
                if (null == data) return;
                Bundle bundle = data.getExtras();
                if (bundle == null) return;
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    switch (bundle.getInt(CodeUtils.STRING_TYPE)) {
                        case com.cryptape.cita_wallet.util.qrcode.CodeUtils.STRING_ADDRESS:
                            String result = bundle.getString(CodeUtils.RESULT_STRING);
                            mCetReceiverAddress.setText(result);
                            break;
                        default:
                            Toast.makeText(this, R.string.address_error,
                                    Toast.LENGTH_LONG).show();
                            break;
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(EntrustActivity.this, R.string.qrcode_handle_fail,
                            Toast.LENGTH_LONG).show();
                }
                break;
            case REQUEST_CODE_TRANSACTION:
                switch (resultCode) {
                    case AdvanceSetupActivity.RESULT_TRANSACTION:
                        mAppTransaction = data.getParcelableExtra(AdvanceSetupActivity.EXTRA_TRANSACTION);
                        mPresenter.updateData(mAppTransaction.data);
                        if (mAppTransaction.isEthereum()) {
                            mPresenter.updateGasLimit(mAppTransaction.getGasLimit());
                            mPresenter.updateGasPrice(mAppTransaction.getGasPrice());
                        } else {
                            mPresenter.updateQuotaLimit(mAppTransaction.getQuota());
                        }
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }
}
